package my12306.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
/*
 * http://www.cnblogs.com/latifrons/archive/2010/07/09/1774458.html
 */

public class HttpClientUtils {

    static final String UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:20.0) Gecko/20130106 Firefox/20.0";
    static final String UserAgentIE = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; NP06; .NET4.0C; .NET4.0E)";
    static final String UserAgentFirefox = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:20.0) Gecko/20130106 Firefox/20.0";

//    public static void main(String[] args) {
//        try {
//            send("");
//        } catch (Exception ex) {
//            Logger.getLogger(HttpClientUtils.class.getName()).log(Level.SEVERE, null, ex);
//        }
//    }

    public static void send(String address) throws Exception {
//        DefaultHttpClient httpclient0 = new DefaultHttpClient();
//        DefaultHttpClient httpclient = getHttpsClient(httpclient0);//关键方法 
        DefaultHttpClient httpclient = getHttpsClient();//关键方法 
        HttpGet httpget = new HttpGet("https://www.google.com");
        // Execute HTTP request 
//        System.out.println("executing request " + httpget.getURI()); 
        HttpResponse response = httpclient.execute(httpget);
        System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            try {
                System.out.println(reader.readLine());
            } catch (IOException ex) {
                throw ex;
            } catch (RuntimeException ex) {
                httpget.abort();
                throw ex;

            } finally {
                reader.close();
            }
        }
        httpclient.getConnectionManager().shutdown();
    }

    public static HttpGet getGet(String url) {
        HttpGet get = new HttpGet(url);
        get.addHeader(HTTP.USER_AGENT, UserAgent);
        return get;
    }

    public static HttpPost getPost(String url) {
        HttpPost post = new HttpPost(url);
        post.addHeader(HTTP.USER_AGENT, UserAgent);
        return post;
    }

//    public static DefaultHttpClient getHttpsClient() {
//        DefaultHttpClient httpClient = new DefaultHttpClient();
//        return getHttpsClient(httpClient);
//    }
    /**
     *
     * @param httpClient
     * @return
     */
    public static DefaultHttpClient getHttpsClient() {
        try {
// First create a trust manager that won't care. 
            X509TrustManager trustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
// Don't do anything. 
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
// Don't do anything. 
                }

                public X509Certificate[] getAcceptedIssuers() {
// Don't do anything. 
                    return null;
                }
            };

// Now put the trust manager into an SSLContext. 
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{trustManager}, null);

// Use the above SSLContext to create your socket factory 
// (I found trying to extend the factory a bit difficult due to a 
// call to createSocket with no arguments, a method which doesn't 
// exist anywhere I can find, but hey-ho). 
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

// If you want a thread safe client, use the ThreadSafeConManager, but 
// otherwise just grab the one from the current client, and get hold of its 
// schema registry. THIS IS THE KEY THING. 
            DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry schemeRegistry = ccm.getSchemeRegistry();

// Register our new socket factory with the typical SSL port and the 
// correct protocol name. 
            schemeRegistry.register(new Scheme("https", sf, 443));

// Finally, apply the ClientConnectionManager to the Http Client 
// or, as in this example, create a new one. 
            DefaultHttpClient result = new DefaultHttpClient(ccm, httpClient.getParams());
            //http://stackoverflow.com/questions/6647530/automate-html-form-submission-using-java-to-find-grocery-hours
            result.setRedirectHandler(new DefaultRedirectHandler() {
                @Override
                public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
                    boolean isRedirect = super.isRedirectRequested(response, context);
                    if (!isRedirect) {
                        int responseCode = response.getStatusLine().getStatusCode();
                        if (responseCode == 301 || responseCode == 302) {
                            return true;
                        }
                    }
                    return isRedirect;
                }
            });
            return result;
        } catch (Throwable t) {
// AND NEVER EVER EVER DO THIS, IT IS LAZY AND ALMOST ALWAYS WRONG! 
            t.printStackTrace();
            return null;
        }
    }
}